#include "verifycodewidget.h"
#include "model/data.h"
#include <QPainter>



VerifyCodeWidget::VerifyCodeWidget(QWidget *parent)
    :QWidget(parent),randGenerator(model::getCurrentTime())
{
    verifyCode = getVerifyCode();
}

QString VerifyCodeWidget::getVerifyCode()
{
    QString code;
    for(int i=0;i<4;i++)
        code+=(QChar)('A'+randGenerator.generate()%26);
    return code;
}

void VerifyCodeWidget::refreshVerifyCode()
{
    verifyCode = getVerifyCode();
    this->update();
}

void VerifyCodeWidget::paintEvent(QPaintEvent *event)
{
    (void)event;
    const int width = 180;
    const int height = 80;

    QPainter painter(this);
    QPen pen;
    QFont font("楷体",25,QFont::Bold,true);
    painter.setFont(font);
    verifyCode = getVerifyCode();
    auto refreshPen=[&]()
    {
        pen = QPen(QColor(randGenerator.generate()%256,randGenerator.generate()%256,randGenerator.generate()%256));
        painter.setPen(pen);
    };

    //画100个随机噪点
    for(int i=0;i<100;i++)
    {
        refreshPen();
        painter.drawPoint(randGenerator.generate()%width,randGenerator.generate()%height);
    }
    //添加10个干扰线
    for(int i =0;i<10;i++)
    {
        refreshPen();
        painter.drawLine(randGenerator.generate()%width,randGenerator.generate()%height,
        randGenerator.generate()%width,randGenerator.generate()%height);
    }
    //绘制验证码
    for(int i=0;i<verifyCode.size();i++)
    {
        refreshPen();
        painter.drawText(5+20*i,randGenerator.generate()%8,30,30,Qt::AlignCenter,QString(verifyCode[i]));
    }
}

void VerifyCodeWidget::mousePressEvent(QMouseEvent *event)
{
    (void)event;
    refreshVerifyCode();
}

bool VerifyCodeWidget::isRight(const QString &VerifyCode)
{
    return !this->verifyCode.compare(VerifyCode,Qt::CaseInsensitive);
}
